package com.py.custom.tms.application.current;

public class VolatileTest {

    private static boolean hasOpen = true;

    private static int x = 0, y = 0;

    private static int a = 0, b = 0;

    private static int p = 0;

    private static boolean z = true;

    public static void main(String[] args) throws Exception {
        volatileRun();
        // reSort();
        // reSort1();
    }

    public static void reSort1() throws Exception {
        Thread one = new Thread(() -> {
            while (z) {//true
            }
            System.out.println(p);//
        });
        Thread two = new Thread(() -> {
            p = 1; // p =1
            z = false; // z =false
        });
        one.start();
        two.start();
    }

    public static void reSort() throws Exception {
        int i = 0;
        while (true) {
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            Thread one = new Thread(() -> {
                a = 1;// a =1, b=0/1
                x = b;// a =1, x=0/1
            });
            Thread two = new Thread(() -> {
                b = 1; // b =1, a=0/1
                y = a;// b=1, y=0/1
            });
            one.start();
            two.start();
            one.join();
            two.join();
            String result = "第" + i + "次 (" + x + "," + y + "）";
            if (x == 0 && y == 0) {
                System.err.println(result);
                break;
            }
        }
    }

    public static void volatileRun() throws Exception {
        System.out.println(Thread.currentThread().getName() + "-----start");
        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "-----start");
            while (hasOpen) {

            }
            System.out.println(Thread.currentThread().getName() + "-----end");
        });

        Thread t2 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "----start");
            hasOpen = false;
            System.out.println(Thread.currentThread().getName() + "----end");
        });
        t1.start();
        Thread.sleep(1000);
        t2.start();
        System.out.println(Thread.currentThread().getName() + "-----end");
    }

}
